
#import "Tex.h"

@implementation Tex

- (void) createTexFromImage: (NSString *) picName {   
    //Load texture    
    NSError *error;
    NSString *path = [[NSBundle mainBundle] pathForResource: picName ofType: @"png"];
    textureInfo = [GLKTextureLoader textureWithContentsOfFile: path 
                                                      options: nil 
                                                        error: &error];
    if (textureInfo && !error) {        
        width = textureInfo.width;
        height = textureInfo.height;        
        if ( (width & (width-1)) != 0 || (height & (height-1)) != 0 
            || width > 2048 || height > 2048) {
            NSLog(@"ERROR: %@ width and/or height is not a power of 2 or > 2048!", picName); 
        }  
        
        //Generate texture
        textureProperty = [[GLKEffectPropertyTexture alloc] init];
        textureProperty.name = textureInfo.name;  
        textureID = textureProperty.name;
        
        glEnable(GL_BLEND);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
        
    } else {
        NSLog(@"ERROR: %@ not found, texture %@ not created.", [error localizedDescription], picName);
    }
}

- (void) drawAt: (CGPoint) p {
    GLshort imageVertices[ ] = {                 
        0,      height, 
        width,  height, 
        0,      0,      
        width,  0      
    };        
    
    GLshort textureCoords[ ] = {                 
        0, 1, 
        1, 1, 
        0, 0, 
        1, 0                       
    };
    
    p.x = (int) p.x;
    p.y = (int) p.y;
    
    glEnable(GL_TEXTURE_2D);  
    
    glColor4f(1, 1, 1, 1);
    glBindTexture(GL_TEXTURE_2D, textureID); 
    glVertexPointer(2, GL_SHORT, 0, imageVertices);	
    glTexCoordPointer(2, GL_SHORT, 0, textureCoords);    
    
    glPushMatrix();
    glTranslatef(p.x, p.y, 0);    
    glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); 
    glPopMatrix();
    
    glDisable(GL_TEXTURE_2D);    
}

- (GLuint) getTextureID {
    return textureID;
}

- (int) getWidth {
    return width;
}

- (int) getHeight {
    return height;
}

- (void) dealloc {
    NSLog(@"Delete texture, ID: %i", textureID);
    glDeleteTextures(1, &textureID);
    [textureProperty release];
    [textureInfo release];
    [super dealloc];
}

@end
